package com.wosai.teach.fragment;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.wosai.teach.R;
import com.wosai.teach.activity.LoginActivity;
import com.wosai.teach.activity.MainActivity;
import com.wosai.teach.adapter.HomeWorkAdapter;
import com.wosai.teach.cst.C;
import com.wosai.teach.dto.JsonResult;
import com.wosai.teach.entity.ExpDateRel;
import com.wosai.teach.entity.Experiment;
import com.wosai.teach.entity.HomeWork;
import com.wosai.teach.entity.User;
import com.wosai.teach.listener.SimuOnItemClickListener;
import com.wosai.teach.service.DownLoadFactory;
import com.wosai.teach.service.DownLoadService;
import com.wosai.teach.utils.AppUtil;
import com.wosai.teach.utils.OtherUtils;
import com.wosai.teach.utils.SynchUtils;

import com.wosai.teach.adapter.SimulationAdapter.ViewHolder;

public class HomeworkFragment extends AppFragment{
	private View view;

	private int pageSize = 10;

	private int curPage = 1;

	private User user;

	private HomeWorkAdapter adapter;
	
	private AppFragment fragment;

	@ViewInject(R.id.hw_list)
	private PullToRefreshListView hwList;
	
	private SimuOnItemClickListener listener;
	
	private DownLoadFactory factory;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.activity_homework, container, false);
		setmPageName("我的作业");
		init();
		initView();
		loadInfo();
		return view;
	}

	private void initView() {
		hwList = (PullToRefreshListView) view.findViewById(R.id.hw_list);
		hwList.setMode(Mode.BOTH);
		List<HomeWork> workList = new ArrayList<HomeWork>();
		adapter = new HomeWorkAdapter(this.getActivity(), workList);
		hwList.setAdapter(adapter);
		hwList.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					final PullToRefreshBase<ListView> refreshView) {
				System.out.println("下拉刷新" + refreshView.getClass());
				curPage = 1;
				loadInfo();
			}

			@Override
			public void onPullUpToRefresh(
					final PullToRefreshBase<ListView> refreshView) {
				System.out.println("上拉加载" + refreshView.getClass());
				curPage++;
				loadInfo();
			}
		});
		
		final FragmentActivity self = this.getActivity();
		
		factory = DownLoadService.getDownLoadManager(getActivity()
				.getApplicationContext());
		listener= new SimuOnItemClickListener(getActivity(), db, factory, this);
		
		hwList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				System.out.println(position);
				HomeWork homework = (HomeWork) parent.getAdapter()
						.getItem(position);

				Experiment exp = db.findFirst(Selector.from(Experiment.class).where(
						"expId", "=", homework.getExpId()));
				PackageInfo pi = AppUtil.getPackageInfo(exp.getApkPackageName());
				int ver = AppUtil.getVersionCode(pi);
				if (ver > 0 && exp.getApkVer() > ver) {
					// 更新
					Intent it = new Intent(getActivity(),MainActivity.class);
					it.putExtra("expId", homework.getExpId());
					getActivity().setResult(C.RESULT_CODE_UPDATE, it);
					startActivity(it);
					getActivity().finish();
				} else if (ver > 0) {
					// 打开apk
					listener.openSoft(exp);
				} else {
					// 下载
					Intent it = new Intent();
					it.putExtra("expId", homework.getExpId());
					getActivity().setResult(C.RESULT_CODE_DOWNLOAD, it);
					getActivity().finish();
				}
				
			}
		});
	}

	private void loadInfo() {
		user = db.findFirst(User.class);
		if (user == null) {
			Toast.makeText(getActivity(), "请先登录", Toast.LENGTH_SHORT)
					.show();
			Intent it = new Intent(this.getActivity(), LoginActivity.class);
			startActivity(it);
		} else {

			String url = C.HTTP_URL_HOME_LIST;
			url = url.replace("{userId}", user.getUserId() + "");
			url = url.replace("{pageSize}", pageSize + "");
			url = url.replace("{currentPage}", curPage + "");
			System.out.println(url);

			HttpUtils http = new HttpUtils();
			http.send(HttpRequest.HttpMethod.GET, url,
					new RequestCallBack<String>() {

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							if (OtherUtils.CheckNull(responseInfo.result)) {
								return;
							}
							JsonResult jr = JSON.parseObject(
									responseInfo.result, JsonResult.class);
							if (jr.getResult() == 0) {
								System.out.println("当前页||" + curPage);
								if (curPage == 1) {
									// 删除数据库
									db.deleteAll(Selector.from(HomeWork.class)
											.where("userId", "=",
													user.getUserId()));
								}
								List<HomeWork> expList = JSON
										.parseArray(jr.getObject().toString(),
												HomeWork.class);
								db.saveAll(expList);
								refreshRecList(expList);
							} else {
								if (curPage == 1) {
									List<HomeWork> expList = db
											.findAll(Selector
													.from(HomeWork.class));
									refreshRecList(expList);
								}
							}
							hwList.onRefreshComplete();
						}

						@Override
						public void onFailure(HttpException error, String msg) {
							if (curPage == 1) {
								List<HomeWork> expList = db.findAll(Selector
										.from(HomeWork.class));
								refreshRecList(expList);
							}
							hwList.onRefreshComplete();
						}
					});

		}

	}

	private void refreshRecList(List<HomeWork> expList) {
		if (curPage == 1) {
			adapter.setList(expList);
		} else {
			adapter.addList(expList);
		}
		adapter.notifyDataSetChanged();
	}
	
}

